package com.liu.shop.listener;

import com.liu.shop.common.constant.OrderConstatns;
import com.liu.shop.common.vo.StockVo;
import com.liu.shop.entity.OrderEntity;
import com.liu.shop.feign.StockService;
import com.liu.shop.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 监听订单超时队列
 */
@Component
@Slf4j
public class OrderTtlDleListener {
    @Autowired
    private OrderService orderService;

    @Autowired
    private StockService stockService;

    /**
     * 这个方法被调用，说明订单已经超过3分钟。要开始修改订单状态
     * 监听订单超时队列，订单超时修改订单状态
     */
    @RabbitListener(queues = OrderConstatns.ORDER_TTL_DLE_QUEUE)
    public void orderTimeOut(String orderId, Channel channel, Message message){
        try {
        // 1.查询订单的最新状态
        OrderEntity orderEntity = orderService.getOrderById(orderId);
        // 2.判断订单的状态，可能已经支付，也有可能取消
        if(orderEntity.getStatus() == 1){// 说明订单未支付，修改订单状态为超时
            orderService.updateOrderStatus(orderId,4);

            // 通知支付宝把交易订单关闭
        }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订单超时一分钟后需要释放库存
     */
    @RabbitListener(queues = OrderConstatns.STOCK_DLE_UNLOCK_QUEUE)
    public void stockFree(String orderId, Channel channel, Message message){
        try {
            // 1.查询订单的最新状态
            OrderEntity orderEntity = orderService.getOrderById(orderId);

            // 2.判断订单的状态是否为超时或者取消
            if(orderEntity.getStatus()==4||orderEntity.getStatus()==3){
                // 3.根据订单编号查询订单中商品的id和数量，进行库存释放
                List<StockVo> stockVoList = orderService.getStockVoListOrderId(orderId);

                if (stockVoList != null && !stockVoList.isEmpty()) {
                    log.debug("库存释放了。。{}", stockVoList);
                    // 4.释放库存
                    stockService.unLockStock(stockVoList);
                }
                // 通知支付宝把交易订单关闭
            }
            // 手动ack，确定消费完成后应答给mq
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
